package controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import db.DbConn;

public class Login extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		DbConn conn = new DbConn();
		conn.setDbUrl(getServletContext().getInitParameter("dbUrl"));
		conn.setDbUser(getServletContext().getInitParameter("dbUser"));
		conn.setDbPass(getServletContext().getInitParameter("dbPass"));

		String userid = req.getParameter("id");
		String userpw = req.getParameter("pw");
		if ("admin".equals(userid) && "admin".equals(userpw)) {
			HttpSession session = req.getSession();
			session.setAttribute("isLogin", (Boolean) true);
			session.setAttribute("userId", userid);
			// 여기서 userId 로
			resp.sendRedirect("logon/logonIndex.jsp");
		} else {

			boolean result = conn.loginUser(userid, userpw);

			if (result == true) {
				HttpSession session = req.getSession();
				session.setAttribute("isLogin", (Boolean) true);
				session.setAttribute("userId", userid);
				
				resp.sendRedirect("logon/logonIndex.jsp");
			} else {
				resp.setContentType("text/html");
				PrintWriter out = resp.getWriter();
				out.println("<script type='text/javascript'>");
				out.println("alert(' Login Fail Retry!');");
				out.println("location.href='login.jsp';");
				out.println("</script>");
				out.flush();
			}
		}
	}
}
